package zgrjb.snbq.teach_platform.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import zgrjb.snbq.teach_platform.interceptor.LoginInterceptor;

/**
 * Web配置类
 * 配置拦截器、CORS等
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/api/**") // 拦截所有API请求
                .excludePathPatterns(
                        "/api/v1/user/register", // 注册接口
                        "/api/v1/user/login",    // 登录接口
                        "/api/v1/user/sendCode", // 发送验证码接口
                        "/api/v1/user/notify",   // 图形验证码接口
                        "/api/v1/user/captcha",  // 图形验证码接口（备用）
                        "/api/v1/health",        // 健康检查
                        "/api/v1/health/**",     // 所有健康检查子端点
                        "/api/v1/chat/**",       // AI聊天接口
                        "/api/v1/upload/**",     // 文件上传接口
                        "/api/v1/test/**",       // 测试接口
                        "/api/v1/database/**",   // 数据库初始化接口
                        "/actuator/**"           // Spring Boot Actuator端点
                );
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置静态资源处理
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/", "classpath:/public/")
                .setCachePeriod(3600);
        
        // 配置上传文件访问
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:uploads/")
                .setCachePeriod(3600);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*") // 允许所有来源（开发环境）
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true) // 允许携带cookie
                .maxAge(3600); // 预检请求缓存时间
    }
} 